package storagews.impl;

import storagews.AbstractFileService;
import core.net.DriveRequest;
import core.net.DropboxRequest;
import core.net.Json;
import core.oauth.ServiceFactory;
import core.pojos.Converter;
import core.pojos.ItemInfo;
import core.pojos.MergedList;
import java.io.IOException;
import java.net.URISyntaxException;
import java.util.Collections;
import java.util.List;
import javax.ws.rs.Path;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Produces;
import storagews.common.PathParam;

/**
 * REST Web Service
 *
 * @author Admin
 */
@Path("files")
public class FileService extends ServiceBase implements AbstractFileService {

    protected List<ItemInfo> listDropbox(String path) throws IOException, URISyntaxException {
        if (!hasToken(ServiceFactory.DROPBOX)) {
            return Collections.emptyList();
        }
        DropboxRequest request = new DropboxRequest(getToken(ServiceFactory.DROPBOX));
        return Converter.fromDir(Json.ToDropboxDir(request.list(path)));
    }

    protected List<ItemInfo> listDrive(String path) throws IOException, URISyntaxException {
        if (!hasToken(ServiceFactory.DRIVE)) {
            return Collections.emptyList();
        }
        DriveRequest request = new DriveRequest(getToken(ServiceFactory.DRIVE));
        return Converter.fromDir(Json.ToDriveDir(request.list(path)));
    }

    @GET
    @Path("list")
    @Produces("application/json")
    @Override
    public List<ItemInfo> list() throws IOException, URISyntaxException {
        MergedList list = new MergedList();
        list.merge(listDropbox(""));
        list.merge(listDrive(""));
        return list.getList();
    }

    @POST
    @Path("list")
    @Produces("application/json")
    @Override
    public List<ItemInfo> openFolder(List<PathParam> paths) throws IOException, URISyntaxException {
        MergedList list = new MergedList();
        for (PathParam param : paths) {
            switch (param.getStorageType()) {
                case ServiceFactory.DROPBOX:
                    list.merge(listDropbox(param.getId()));
                    break;
                case ServiceFactory.DRIVE:
                    list.merge(listDrive(param.getId()));
                    break;
                case ServiceFactory.ONEDRIVE:
                    break;
            }
        }
        return list.getList();
    }
}
